package course.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import course.pojo.entity.College;
import course.pojo.entity.Subject;
import course.pojo.vo.Page;
import course.service.CollegeService;
import course.service.SubjectService;
import course.service.impl.CollegeServiceImpl;
import course.service.impl.SubjectServiceImpl;
import org.apache.commons.lang.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author HLF
 * @date 2022/7/1 18:20
 */
@WebServlet("/admin/subjectController")
public class SubjectController extends BaseController {
    private SubjectService subjectService = new SubjectServiceImpl();

    private CollegeService collegeService = new CollegeServiceImpl();

    /**
     * 跳转到subject_manage.jsp
     */
    protected void index(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String pageNo = req.getParameter("pageNo");
        this.main(req, resp, pageNo);
    }

    protected void main(HttpServletRequest req, HttpServletResponse resp, String pageNo) throws ServletException, IOException {
        if (pageNo == null || Integer.parseInt(pageNo) <= 0) {
            pageNo = "1";
        }

        Page<Subject> page = subjectService.page(Integer.valueOf(pageNo));

        req.setAttribute("page", page);
        req.getRequestDispatcher("/subject_manage.jsp").forward(req, resp);
    }

    /**
     * 添加课程
     */
    protected void add(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String suname = req.getParameter("suname");
        String cid = req.getParameter("cid");
        College college = collegeService.getById(Integer.valueOf(cid));
        String cname = college.getCname();

        String total = req.getParameter("total");
        String pages = req.getParameter("pages");


        Integer pageSize = new Page<>().getPageSize();

        Integer pages2 = Integer.valueOf(pages);
        if (Integer.parseInt(total) % pageSize == 0) {
            pages2 += 1;
        }

        Subject subject = new Subject(null, suname, Integer.valueOf(cid), cname);
        int i = subjectService.addSubject(subject);
        if (i > 0) {
            this.main(req, resp, String.valueOf(pages2));
        }
    }

    /**
     * 删除课程
     */
    protected void delete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String suid = req.getParameter("suid");
        String pn = req.getParameter("pn");

        int i = subjectService.deleteById(Integer.valueOf(suid));
        if (i > 0) {
            Page<Subject> page = subjectService.page(Integer.valueOf(pn));

            req.setAttribute("page", page);
            req.getRequestDispatcher("/subject_manage.jsp").forward(req, resp);
        }
    }

    /**
     * 批量删除所有选中课程
     */
    protected void deleteSelect(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String[] ids = req.getParameterValues("ids[]");

        List<String> list = Arrays.asList(ids);
        List<Integer> integers = list.stream().map(Integer::valueOf).collect(Collectors.toList());

        int i = subjectService.deleteSelect(integers);
        if (i > 0) {
            this.index(req, resp);
        }
    }

    /**
     * 通过suid获取subject对象
     */
    protected void getSubject(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=UTF-8");
        String suid = req.getParameter("suid");

        Subject subject = subjectService.getById(Integer.valueOf(suid));
        ObjectMapper mapper = new ObjectMapper();

        String jsonString = mapper.writeValueAsString(subject);
        PrintWriter writer = resp.getWriter();
        writer.write(jsonString); //将json对象响应给前端
        writer.flush();
    }

    /**
     * 修改课程
     */
    protected void update(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String suid = req.getParameter("suid");
        String suname = req.getParameter("suname");
        String cid = req.getParameter("cid");


        College college = collegeService.getById(Integer.valueOf(cid));
        String cname = college.getCname();

        String pn = req.getParameter("pn");

        Subject subject = new Subject(Integer.valueOf(suid), suname, Integer.valueOf(cid), cname);

        int i = subjectService.updateById(subject);
        if (i > 0) {
            this.main(req, resp, pn);
        }
    }

    /**
     * 查询所有课程数量
     */
    protected void count(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=UTF-8");

        long count = subjectService.count();
        PrintWriter writer = resp.getWriter();
        writer.println(count);
        writer.flush();
    }

    /**
     * 根据课程名查询课程信息
     */
    protected void query(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        String suname = req.getParameter("suname");

        String pageNo = req.getParameter("pageNo");
        if (pageNo == null || Integer.parseInt(pageNo) <= 0) {
            pageNo = "1";
        }

        Page<Subject> page = subjectService.query(suname, Integer.valueOf(pageNo));

        req.setAttribute("suname",suname);
        req.setAttribute("page", page);
        req.getRequestDispatcher("/subject_manage.jsp").forward(req, resp);
    }

    /**
     * 跳转到添加课程的模态框
     * subject_add.jsp需要所有学院信息
     */
    protected void addPage(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        List<College> list = collegeService.getList();
        req.setAttribute("list", list);
        req.getRequestDispatcher("/subject_add.jsp").forward(req, resp);
    }

    /**
     * 跳转到修改课程的模态框
     */
    protected void updatePage(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String suid = req.getParameter("suid");
        String pageNo = req.getParameter("pageNo");


        Subject subject = subjectService.getById(Integer.valueOf(suid));
        req.setAttribute("subject", subject);

        List<College> list = collegeService.getList();
        req.setAttribute("list", list);
        req.getRequestDispatcher("/subject_update.jsp").forward(req, resp);

    }

    /**
     * 通过课程名判断该课程是否存在
     */
    protected void exit(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=UTF-8");
        PrintWriter writer = resp.getWriter();
        ObjectMapper mapper = new ObjectMapper();
        //响应给前端的code,msg
        Map<String, Object> result = new HashMap<>();

        String suname = req.getParameter("suname");

        if (StringUtils.isBlank(suname)) {
            result.put("code", 0);
            result.put("msg", "课程不能为空！");
            writer.println(mapper.writeValueAsString(result));
            return;
        }

        Subject bySuname = subjectService.getBySuname(suname);
        if (bySuname != null) {
            result.put("code", 0);
            result.put("msg", "该课程已经存在！");
            writer.println(mapper.writeValueAsString(result));
            return;
        }
        result.put("code", 1);
        result.put("msg", "该课程不存在，可以新增");
        writer.println(mapper.writeValueAsString(result));
    }

    /**
     * 通过课程名判断该课程是否存在2
     */
    protected void exit2(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=UTF-8");
        PrintWriter writer = resp.getWriter();
        ObjectMapper mapper = new ObjectMapper();
        //响应给前端的code,msg
        Map<String, Object> result = new HashMap<>();

        String suname = req.getParameter("suname");
        String psuname = req.getParameter("psuname");

        System.out.println(psuname);

        if (StringUtils.isBlank(suname)) {
            result.put("code", 0);
            result.put("msg", "课程不能为空！");
            writer.println(mapper.writeValueAsString(result));
            return;
        }

        Subject bySuname = subjectService.getBySuname(suname);
        if (bySuname != null && !bySuname.getSuname().equals(psuname)) {
            result.put("code", 0);
            result.put("msg", "该课程已经存在！");
            writer.println(mapper.writeValueAsString(result));
            return;
        }
        result.put("code", 1);
        result.put("msg", "该课程不存在，可以新增");
        writer.println(mapper.writeValueAsString(result));
    }
}
